﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kugar.Core.Security
{
    public class RMS_UserPermissionManager
    {
        private Lazy<RMS_PermissionValueCollection> _permissionList=null;
        private int _currentUserID = 0;
        private IUserPermissionChecker _provider = null;

        public RMS_UserPermissionManager(int userID, IUserPermissionChecker provider)
        {
            if (provider==null)
            {
                throw new ArgumentNullException("provider");
            }

            if (userID<=0)
            {
                throw new ArgumentOutOfRangeException("userID");
            }

            _currentUserID = userID;
            _provider = provider;
            _permissionList = new Lazy<RMS_PermissionValueCollection>(GetUserPermissionList,true);
        }

        public RMS_PermissionValueCollection Permissions { get { return _permissionList.Value; } }

        protected virtual RMS_PermissionValueCollection GetUserPermissionList()
        {
            return _provider.GetPermissionListByUserID();
        }

        public bool HasPermission(string permissionName)
        {
            if (_permissionList.IsValueCreated)
            {
                return _permissionList.Value.HasPermission(permissionName);
            }
            else
            {
                return OnCheckPermissionByName(permissionName) != 0;
            }
            
        }

        public bool HasPermission(int permissionID)
        {
            if (_permissionList.IsValueCreated)
            {
                return _permissionList.Value.HasPermission(permissionID);
            }
            else
            {
                return OnCheckPermissionByID(permissionID) != 0;
            }
            
        }

         protected virtual int OnCheckPermissionByID(int permissionID)
         {
             return _permissionList.Value.GetPermissionValue(permissionID);
             //return _provider.CheckPermissionByID(permissionID);
         }

         protected virtual int OnCheckPermissionByName(string permissionName)
         {
             return _permissionList.Value.GetPermissionValue(permissionName);
             //return _provider.CheckPermissionByName(permissionName);
         }
             

    }
}
